#include <stdio.h>
#include "csapp.h"

struct Object
{
    char* head;
    char* body;
    int bodysize;
};

/* receive_reponse - receive reponse from the server
 *                   store the reponse HTTP buf and body in the struct Object
 * return value:
 * 1 - success
 * 0 - error
 */

int receive_response(int fd, struct *Object){
    rio_t rio;
    char buf[MAXLINE];
    char temp[MAXLINE];

    Rio_readinitb(&rio, fd);
    Object->head = malloc(MAXBUF);
    int count = 1;
    while(strcmp(buf, "\r\n") != 0){
        Rio_readlineb(&rio, buf, MAXLINE);
        sprintf(Object->head, "%s%s", Object->head, buf);
        if(count == 3){
            sscanf(buf, "%sContent-length: %d", temp, Object->bodysize); 
            Object->bodysize = ntohl(Object->bodysize); 
        }
        count ++;
    }

    Object->body = malloc(Object->bodysize);
    Rio_readnb(rp, Object->body, Object->bodysize);
        
    return 1;
}


/* send_response - send the reponse got from server(storing in Object)
 *                 to client
 */
int send_response(int fd, struct *Object){

    Rio_writen(fd, Object->head, strlen(Object->head));
    Rio_writen(fd, Object->body, Object->bodysize);
    return 1;
}


    

    
